package main

import (
	"fmt"
	"net/http"
	"os"
	"os/exec"
	"time"
)

const (
	proxyIP   = "127.0.0.1"
	socksPort = "20170"
	httpPort  = "20171"
)

var (
	phttp  = fmt.Sprintf("http://%s:%s", proxyIP, httpPort)
	psocks = fmt.Sprintf("socks5://%s:%s", proxyIP, socksPort)
)

func setProxy() {
	os.Setenv("http_proxy", phttp)
	os.Setenv("HTTP_PROXY", phttp)
	os.Setenv("https_proxy", phttp)
	os.Setenv("HTTPS_PROXY", phttp)
	os.Setenv("all_proxy", psocks)
	os.Setenv("ALL_PROXY", psocks)

	exec.Command("git", "config", "--global", "http.https://github.com.proxy", phttp).Run()
	exec.Command("git", "config", "--global", "https.https://github.com.proxy", phttp).Run()

	fmt.Println("Proxy has been open.")
}

func unsetProxy() {
	os.Unsetenv("http_proxy")
	os.Unsetenv("HTTP_PROXY")
	os.Unsetenv("https_proxy")
	os.Unsetenv("HTTPS_PROXY")
	os.Unsetenv("all_proxy")
	os.Unsetenv("ALL_PROXY")

	exec.Command("git", "config", "--global", "--unset", "http.https://github.com.proxy").Run()
	exec.Command("git", "config", "--global", "--unset", "https.https://github.com.proxy").Run()

	fmt.Println("Proxy has been closed.")
}

func testSettings() {
	fmt.Println("Try to connect to Google...")
	client := &http.Client{
		Timeout: 5 * time.Second,
	}
	resp, err := client.Head("https://www.google.com")
	if err != nil {
		fmt.Println("Proxy setup failed!")
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode == 200 {
		fmt.Println("Proxy setup succeeded!")
	} else {
		fmt.Println("Proxy setup failed!")
	}
}

func main() {
	if len(os.Args) < 2 {
		fmt.Println("Unsupported arguments.")
		return
	}

	switch os.Args[1] {
	case "set":
		setProxy()
	case "unset":
		unsetProxy()
	case "test":
		testSettings()
	default:
		fmt.Println("Unsupported arguments.")
	}
}
